package com.diorsunion.hedge.bo.datasync;

import com.diorsunion.hedge.bo.db.StockPriceBO;
import com.diorsunion.hedge.bo.net.DataFetcher;
import com.diorsunion.hedge.util.CalendarUtils;
import com.diorsunion.hedge.common.Period;
import com.diorsunion.hedge.dal.entity.Stock;
import com.diorsunion.hedge.dal.entity.StockPrice;
import com.diorsunion.hedge.dal.repository.StockPriceRepository;
import com.diorsunion.hedge.dal.repository.StockRepository;
import com.diorsunion.hedge.web.util.LogUtil;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 股票数据同步抽象父类
 * Created by harley-dog<custer7572@163.com> on 2015/12/12.
 */
public abstract class StockDataSync {

    @Resource
    protected StockPriceRepository stockPriceRepository;
    @Resource
    protected StockRepository stockRepository;
    @Resource
    DataFetcher dataFetcher;
    @Resource
    StockPriceBO stockPriceBO;

    protected abstract Period getPeriod();

    protected abstract Date getBegin(Date date, Stock stock);

    protected abstract Date getEnd(Date date, Stock stock);

    /**
     * 同步数据到数据库
     *
     * @param date  同步截至的日期(可以认为是endDate)
     * @param stock 要同步的股票 (需要id,code两个字段)
     * @throws Exception
     */
    public void sync(Date date, Stock stock) throws Exception {
        Period period = getPeriod();
        Date begin = getBegin(date, stock);
        Date end = getEnd(date, stock);
        LogUtil.info(LogUtil.task, period + " sync [" + CalendarUtils.formatFull(begin) + " ~ " + CalendarUtils.formatFull(begin) + "] ,stock:" + stock);
        /*先从网上巴拉下来数据*/
        List<StockPrice> stockPriceList = dataFetcher.fetchStockPrice(stock, begin, end, period);
        /*然后再一条条插入到数据库里去*/
        stockPriceList.stream()
                .sorted((x, y) -> x.thedate.compareTo(y.thedate))
                .forEach(stockPrice -> stockPriceBO.insert(stock, stockPrice, getPeriod()));
    }


}
